package resp

import (
	"encoding/json"
	"fmt"
	"net/http"
)

// 返回结果
type Resp struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func NewResp(code int, msg string, data interface{}) *Resp {
	return &Resp{Code: code, Msg: msg, Data: data}
}

func NewRespAndWriteDirect(code int, msg string, data interface{}, writer http.ResponseWriter) {
	r := NewResp(code, msg, data)
	r.WriteResp(writer)
}

func (r *Resp) WriteResp(writer http.ResponseWriter) {
	bs, _ := json.Marshal(r)
	_, err := writer.Write(bs)
	if err != nil {
		fmt.Println(err)
	}
}
